# 作者: YYJ
# 2025年07月08日13时22分46秒
# 2486249622@qq.com

import socket
import sys

import select

class ChatClient:
    def __init__(self, host, port):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client.connect((host, port))
        self.epoll = select.epoll()

    def chat_client(self):
        self.epoll.register(self.client.fileno(), select.EPOLLIN)   # 监控连接（读事件）
        self.epoll.register(sys.stdin.fileno(), select.EPOLLIN)   # 监控标准输入
        while True:
            events = self.epoll.poll(-1)
            for fd, event in events:
                if fd == self.client.fileno():  # 服务器发来数据
                    if event & select.EPOLLIN:
                        data = self.client.recv(1024).decode('utf-8')
                        if data:
                            print("Server:", data)
                        else:
                            print('服务器已关闭')
                            return
                elif fd == sys.stdin.fileno():  # 客户端发出数据，写到连接里
                    msg = input()
                    self.client.send(msg.encode('utf-8'))

if __name__ == '__main__':
    client = ChatClient('127.0.0.1', 8000)
    client.chat_client()